package com.imooc.zk.demo;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.AsyncCallback.ChildrenCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

/**
 * zookeeper 获取子节点数据的demo演示
 * 
 * @author wb0024
 *
 */

public class ZKGetChildrenList implements Watcher {

	public static String zkServerPath = "47.104.64.192:2181";
	public static final Integer timeout = 5000;
	public static Stat stat;
	private ZooKeeper zookeeper = null;
	private static CountDownLatch countDown = new CountDownLatch(1);

	public ZKGetChildrenList() {
	}

	public ZKGetChildrenList(String zkserverpath) {
		try {
			zookeeper = new ZooKeeper(zkserverpath, timeout, new ZKNodeOperator());
		} catch (IOException e) {
			e.printStackTrace();
			if (zookeeper != null) {
				try {
					zookeeper.close();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) throws Exception {
		ZKGetChildrenList zkServer = new ZKGetChildrenList(zkServerPath);

		List<String> strChildList = zkServer.getZookeeper().getChildren("/imooc", true);
		for (String s : strChildList) {
			System.out.println(s);
		}
		
		//异步调用
//		String ctx = "{'callback':'ChildrenCallBack'}";
//		zkServer.getZookeeper().getChildren("/imooc", true, new ChildrenCallBack(),ctx);
//		zkServer.getZookeeper().getChildren("/imooc", true, new Children2CallBack(),ctx);
	
		countDown.await();
	}

	private ZooKeeper getZookeeper() throws IOException {
		ZooKeeper keeper = new ZooKeeper(zkServerPath, timeout, new ZKGetChildrenList());
		return keeper;
	}

	@Override
	public void process(WatchedEvent event) {
		try {
			if (event.getType() == EventType.NodeChildrenChanged) {
				System.out.println("NodeChildrenChanged");
				ZKGetChildrenList zkServer = new ZKGetChildrenList(zkServerPath);
				List<String> strChilder = zkServer.getZookeeper().getChildren(event.getPath(), new ZKGetChildrenList());
				for (String s : strChilder) {
					System.out.println(s);
				}
				countDown.await();
			} else if (event.getType() == EventType.NodeCreated) {
				System.out.println("NodeCreated");
			} else if (event.getType() == EventType.NodeDataChanged) {
				System.out.println("NodeDataChanged");
			} else if (event.getType() == EventType.NodeDeleted) {
				System.out.println("NodeDeleted");
			}
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
